<?php 
namespace Home\Controller;
use Think\Controller;
class UserController extends Controller{
	
	/**
	 * 绑定手机
	 */
	public function bangding(){
		$uid = I('uid');
		if(!$uid){
			redirect(U('Weixin/Auth/index'));
		}
		$this->uid = $uid;
		$this->display();
	}
	
	public function bangding_next(){
		$this->mobile = I('mobile');
		$this->display();
	}
	
	public function realname(){
		$this->mobile = I('mobile');
		$this->display();
	}
	
	//保存绑定信息
	public function dosave(){
		$m = M('Users');
		$sms =D('Sms');
		
		$mobile = I('mobile');
		$code = I('code');
		$uid = I('uid');
		if(!$sms->where(array('mobile'=>$mobile,'code'=>$code,'type'=>'bangding','token_time'=>array('gt',time())))->find()){
			$this->error('验证码不正确');
		}else{
			$user = $m->where(array('uid'=>$uid))->find();
			$info = $m->where(array('mobile'=>$mobile,'uid'=>array('neq',$uid)))->find();
			if($info){
				//手机号码已存在，则更新openid信息
				$data = array(
						'uid' => $info['uid'],
						'openid' => $user['openid'],
						'nickname' => $user['nickname'],
						'sex' => $user['sex'],
						'city' => $user['city'],
						'province' => $user['province'],
						'country' => $user['country'],
						'headimgurl' =>$user['headimgurl'],
						//'type' => 'weixin',
						//'realname' => I('realname'),
						//'mobile' => $mobile,
						'update_time' => Date('Y-m-d H:i:s')
				);
				R('Api/UserDelete/user_delete_info',array($uid,$user,$info['uid'],$mobile,$info));
				$m->where(array('uid'=>$uid))->delete();
			}else{
				$data = array(
						'uid' => $uid,
						'realname' => I('realname'),
						'mobile' => $mobile,
						'update_time' => Date('Y-m-d H:i:s'),
				);
			}
			if($m->save($data)){
				//更新用户表的uid
				R('Api/Student/users_relation_by_tel',array($data['uid'],$mobile));
				//生成缓存
				$users = $m->where(array('uid'=>$data['uid']))->find();
				session('_loginUser_home',$users);
					
				//跳转session
				if($_SESSION['_go']){
					$url = $_SESSION['_go'];
					session('_go',null);//删除session
				}else{
					$url = U('Home/my/index');
				}
				$this->success('保存成功',$url);
			}else{
				$this->error('保存失败');
			}	
		}
	}
}
?>